/**
 * 路由权限守卫组件
 * 用于保护需要特定权限的页面路由
 */

import React, { useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Result, Button, Spin } from 'antd';
import { ExclamationCircleOutlined, HomeOutlined } from '@ant-design/icons';
import { 
  checkCurrentUserRoutePermission, 
  getCurrentUserPermissions,
  type UserPermissions 
} from '../utils/routePermission';

interface PermissionGuardProps {
  children: React.ReactNode;
  requiredRoute?: string; // 如果不提供，使用当前路由
  fallbackPath?: string;  // 无权限时跳转的路径，默认为首页
}

const PermissionGuard: React.FC<PermissionGuardProps> = ({ 
  children, 
  requiredRoute,
  fallbackPath = '/'
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(true);
  const [hasPermission, setHasPermission] = useState(false);
  const [userPermissions, setUserPermissions] = useState<UserPermissions | null>(null);

  // 获取需要检查的路由
  const routeToCheck = requiredRoute || location.pathname;

  useEffect(() => {
    const checkPermission = () => {
      setLoading(true);
      
      // 获取用户信息 - 由于AuthGuard已经检查过登录状态，这里只需要检查权限
      const userInfo = localStorage.getItem('user');
      if (!userInfo) {
        // 理论上不应该到达这里，因为AuthGuard已经处理了
        setHasPermission(false);
        setLoading(false);
        return;
      }

      try {
        const user = JSON.parse(userInfo);
        
        console.log('PermissionGuard - 用户信息:', user);
        console.log('PermissionGuard - 用户level:', user.level, '类型:', typeof user.level);
        
        // level=1的管理员拥有所有权限，直接通过
        if (user.level == 1 || user.level === "1") {
          console.log('PermissionGuard - 管理员用户，直接通过权限验证');
          setHasPermission(true);
          setUserPermissions({ modules: [], level: 1 });
          setLoading(false);
          return;
        }

        // 其他用户需要检查权限
        const permissions = getCurrentUserPermissions();
        setUserPermissions(permissions);

        if (!permissions) {
          // 无权限信息，可能是数据损坏
          setHasPermission(false);
          setLoading(false);
          return;
        }

        // 检查路由权限
        const hasAccess = checkCurrentUserRoutePermission(routeToCheck);
        setHasPermission(hasAccess);
        setLoading(false);
      } catch (error) {
        console.error('解析用户信息失败:', error);
        setHasPermission(false);
        setLoading(false);
      }
    };

    checkPermission();
  }, [routeToCheck, location.pathname]);

  // 处理返回首页
  const handleGoHome = () => {
    navigate(fallbackPath);
  };

  // 处理返回上一页
  const handleGoBack = () => {
    if (window.history.length > 1) {
      navigate(-1);
    } else {
      handleGoHome();
    }
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '60vh' 
      }}>
        <Spin size="large" tip="验证权限中..." />
      </div>
    );
  }

  if (!hasPermission) {
    return (
      <div style={{ padding: '50px 0' }}>
        <Result
          status="403"
          title="403"
          subTitle="抱歉，您没有访问此页面的权限。"
          icon={<ExclamationCircleOutlined style={{ color: '#faad14' }} />}
          extra={
            <div style={{ textAlign: 'center' }}>
              <p style={{ 
                marginBottom: 24, 
                color: '#666',
                fontSize: '14px'
              }}>
                当前用户级别：{userPermissions?.level ? `${userPermissions.level}级` : '未知'}
                <br />
                访问此页面需要相应的系统权限，请联系管理员为您分配权限。
              </p>
              <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
                <Button type="primary" icon={<HomeOutlined />} onClick={handleGoHome}>
                  返回首页
                </Button>
                <Button onClick={handleGoBack}>
                  返回上一页
                </Button>
              </div>
            </div>
          }
        />
      </div>
    );
  }

  return <>{children}</>;
};

export default PermissionGuard;